package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import java.nio.charset.Charset

@Suppress("ClassName")
class `79Wx` : BaseBookHandler() {

    override val host: String = "www.79wx.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val regex = Regex("(http|https)://$host/html/[0-9]+/[0-9]+/")
        if (!regex.matches(url)) {
            throw IllegalStateException("不支持的url， 示例: https://www.79wx.com/html/43/43549/")
        }

        val name = document.select("#info > h1").text().trim()
        val author = document.select("#info > p:nth-child(4)").text().trim().split("：").last()
        val coverUrl = document.select("#fmimg > img").first()?.attr("src")?.let {
            url.toHttpUrl()
                .resolve(it)
                .toString()
        }

        return BookMetaEntity(
            name = name,
            url = url,
            menuUrl = url,
            author = author,
            coverImageUrl = coverUrl,
        )
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = ArrayList<ChapterMetaEntity>()
        val elements = document.select("body > div.listmain > dl > dd")

        for ((index, element) in elements.withIndex()) {
            val name = element.text().trim()
            val url = element.select("a").first()!!.attr("href").let {
                menuUrl.toHttpUrl()
                    .resolve(it)
                    .toString()
            }

            val chapter = ChapterMetaEntity(
                name = name,
                index = index,
                url = url,
                element = element,
            )
            result.add(chapter)
        }

        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity {
        val name = chapterMetaEntity.name
        val doc = chapterMetaEntity.url.toHttpUrl().toDocument()

        val text = doc?.select("#content")?.first()?.wholeText()
            ?: throw IllegalStateException("$name 内未找到内容")

        return ChapterEntity(
            name = name,
            index = chapterMetaEntity.index,
            text = text,
        )
    }

    override fun forceCharset(): Charset {
        return Charset.forName("gbk")
    }
}